package com.tanhua.server.service;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.RelativeDateFormat;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Movements;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.PicUploadResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @description:实现接口功能
 * @author: 浩克
 * @date: Created in 2021/2/22 19:40
 */
@Service
@Repository
public class MovementsService {

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * @description:发布动态
     * @date 2021/2/22 19:51t
     */
    public String saveMovements(String textContent,
                                 String location,
                                 String longitude,
                                 String latitude,
                                 MultipartFile[] multipartFile) {

        User user = UserThreadLocal.get();

        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);

        //图片上传
        List<String> imageUrls = new ArrayList<>();
        for (MultipartFile file : multipartFile) {
            PicUploadResult picUploadResult = this.picUploadService.upload(file);
            imageUrls.add(picUploadResult.getName());
        }

        publish.setMedias(imageUrls);

        return this.quanZiApi.savePublish(publish);
    }


    /**
     * @description:动态查询
     * @date 2021/2/23 16:15
     * @param page
     * @param pageSize
     * @return
     */
    private PageResult queryPublishList(User user, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        Long userId = null;  //默认查询推荐动态

        PageInfo<Publish> pageInfo = null;

        if (null == user){
            //查询推荐动态
            String key = "QUANZI_PUBLISH_RECOMMEND_" + UserThreadLocal.get().getId();
            String value = this.redisTemplate.opsForValue().get(key);
            if (StringUtils.isNotEmpty(value)){
                //命中数据
                String[] pids = StringUtils.split(value, ',');
                int startIndex = (page -1) * pageSize;
                if (startIndex < pids.length){
                    int endIndex = startIndex + pageSize - 1;
                    if (endIndex >= pids.length){
                        endIndex = pids.length - 1;
                    }

                    List<Long> pidList = new ArrayList<>();
                    for (int i = startIndex; i < endIndex; i++) {
                        pidList.add(Long.valueOf(pids[i]));
                    }

                    List<Publish> publishList = this.quanZiApi.queryPublishByPids(pidList);
                    pageInfo = new PageInfo<>();
                    pageInfo.setRecords(publishList);
                }
            }
        }

        if (pageInfo == null){
            //默认查询逻辑
            if (user != null){
                //查询好友动态
                userId = user.getId();
            }

            pageInfo = this.quanZiApi.queryPublishList(userId, page, pageSize);
        }

        user = UserThreadLocal.get();  //查询完成后,还是要获取到当前登录用户id

        pageResult.setCounts(0);
        pageResult.setPages(0);
        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);

        List<Publish> records = pageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)){
            //未查询到动态数据
            return pageResult;
        }

        pageResult.setItems(this.fillValueMovements(records));

        return pageResult;
    }

    /**
     * @description:数据填充
     *
     * @param records
     * @return java.util.List<com.tanhua.server.vo.Movements>
     */
    private List<Movements> fillValueMovements(List<Publish> records){
        User user = UserThreadLocal.get();
        List<Movements> movementsList = new ArrayList<>();
        List<Long> userIds = new ArrayList<>();
        for (Publish record : records) {
            Movements movements = new Movements();

            movements.setId(record.getId().toHexString());
            movements.setUserId(record.getUserId());

            if (!userIds.contains(record.getUserId())){
                userIds.add(record.getUserId());
            }

            String likeUserCommendKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + movements.getId();
            movements.setHasLiked(this.redisTemplate.hasKey(likeUserCommendKey) ? 1 : 0);  //是否点赞

            String likeCommendKey = "QUANZI_COMMENT_LIKE_" + movements.getId();
            String value = this.redisTemplate.opsForValue().get(likeCommendKey);
            if (StringUtils.isNotEmpty(value)){
                movements.setLikeCount(Integer.valueOf(value));   //点赞数
            }else {
                movements.setLikeCount(0);  //点赞数
            }

            String LoveUserCommendKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + movements.getId();
            movements.setHasLoved(this.redisTemplate.hasKey(LoveUserCommendKey) ? 1 : 0);  //是否喜欢

            String loveCommendKey = "QUANZI_COMMENT_LOVE_" + movements.getId();
            String loveValue = this.redisTemplate.opsForValue().get(loveCommendKey);
            if (StringUtils.isNotEmpty(loveValue)){
                movements.setLoveCount(Integer.valueOf(loveValue));   //喜欢数
            }else {
                movements.setLoveCount(0);  //喜欢数
            }

            movements.setLoveCount(100);  //TODO 喜欢数

            movements.setHasLoved(1);  //TODO  是否喜欢

            movements.setDistance("0.2公里");  //距离

            movements.setCommentCount(300);  //TODO 评论数
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));  //发布时间
            movements.setTextContent(record.getText());
            movements.setImageContent(record.getMedias().toArray(new String[]{}));

            movementsList.add(movements);
        }

        //查询用户信息,填充数据
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(userInfoQueryWrapper);

        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfoList) {
                if (movements.getUserId().longValue() == userInfo.getUserId().longValue()){

                    movements.setTags(StringUtils.split(userInfo.getTags(), ','));
                    movements.setNickname(userInfo.getNickName());
                    movements.setGender(userInfo.getSex().name().toLowerCase());
                    movements.setAvatar(userInfo.getLogo());
                    movements.setAge(userInfo.getAge());

                    break;
                }
            }
        }
        return movementsList;
    }


    /**
     * @description:推荐动态查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        return this.queryPublishList(null, page, pageSize);
    }

    /**
     * @description:用户自己的动态查询
     *
     * @param page
     * @param pageSize
     */
    public PageResult queryUserPublishList(Integer page, Integer pageSize) {
        return this.queryPublishList(UserThreadLocal.get(), page, pageSize);
    }


    /**
     * @description:动态点赞
     *
     * @param publishId
     * @return Long
     */
    public Long likeComment(String publishId) {
        User user = UserThreadLocal.get();

        boolean bool = this.quanZiApi.saveLikeComment(user.getId(), publishId);
        if (!bool){
            //保存失败
            return null;
        }
        //保存成功,获取点赞数
        Long likeCount = 0L;
        String likeCommendKey = "QUANZI_COMMENT_LIKE_" + publishId;
        if (!this.redisTemplate.hasKey(likeCommendKey)){
            Long count = this.quanZiApi.queryCommentCount(likeCommendKey, 1);
            likeCount = count;
            this.redisTemplate.opsForValue().set(likeCommendKey, String.valueOf(likeCount));
        }else {
            likeCount = this.redisTemplate.opsForValue().increment(likeCommendKey);
        }

        //记录当前用户已经点赞
        String likeUserCommendKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.opsForValue().set(likeUserCommendKey, "1");

        return likeCount;
    }


    /**
     * @description:取消点赞
     *
     * @param publishId
     */
    public Long disLikeComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean bool = this.quanZiApi.removeComment(user.getId(), publishId, 1);
        if (!bool){
            return null;
        }

        //redis中点赞数减1
        String likeCommendKey = "QUANZI_COMMENT_LIKE_" + publishId;
        Long count = this.redisTemplate.opsForValue().decrement(likeCommendKey);

        //删除啊该用户的点赞标记
        String likeUserCommendKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.delete(likeUserCommendKey);

        return count;
    }


    /**
     * @description: 喜欢操作
     *
     * @param publishId
     * @return Long
     */
    public Long loveCommend(String publishId) {
        User user = UserThreadLocal.get();

        boolean bool = this.quanZiApi.saveLoveComment(user.getId(), publishId);
        if (!bool){
            //保存失败
            return null;
        }
        //保存成功,获取喜欢数
        Long loveCount = 0L;
        String likeCommendKey = "QUANZI_COMMENT_LOVE_" + publishId;
        if (!this.redisTemplate.hasKey(likeCommendKey)){
            Long count = this.quanZiApi.queryCommentCount(likeCommendKey, 1);
            loveCount = count;
            this.redisTemplate.opsForValue().set(likeCommendKey, String.valueOf(loveCount));
        }else {
            loveCount = this.redisTemplate.opsForValue().increment(likeCommendKey);
        }

        //记录当前用户已经喜欢
        String likeUserCommendKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.opsForValue().set(likeUserCommendKey, "1");

        return loveCount;
    }


    /**
     * @description:取消喜欢
     *
     * @param publishId
     */
    public Long unLoveCommend(String publishId) {
        User user = UserThreadLocal.get();
        boolean bool = this.quanZiApi.removeComment(user.getId(), publishId, 3);
        if (!bool){
            return null;
        }

        //redis中喜欢数减1
        String likeCommendKey = "QUANZI_COMMENT_LOVE_" + publishId;
        Long count = this.redisTemplate.opsForValue().decrement(likeCommendKey);

        //删除啊该用户的喜欢标记
        String likeUserCommendKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.delete(likeUserCommendKey);

        return count;
    }


    /**
     * @description:查询单条动态信息
     *
     * @param publishId
     * @return com.tanhua.server.vo.Movements
     */
    public Movements queryMovementById(String publishId) {
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if (null == publish){
            return null;
        }

        //查询到动态数据,数据填充
        List<Movements> movementsList = this.fillValueMovements(Arrays.asList(publish));

        return movementsList.get(0);

    }
}

